package com.lam.common.utils.uuid;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Random;

import com.lam.common.utils.DateUtil;
import com.lam.common.utils.NumberUtil;
import com.lam.common.utils.StringUtils;

/**
 * 生成主键ID
 */
public class IdGen {
	
	/** 基础字符 1-9，A-Z，a-y，共60个, 0作为特殊字符填充占位，z作为特殊字符进1占位 */
	private static final char[] NUM_TO_CHAR_DICT = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxy".toCharArray();
	
	public static void main(String[] args) {
		System.out.println(genRandom(8));
		System.out.println(generateId());
		System.out.println(generateId());
		System.out.println(generateId());
	}
	
	/**
	 * 随机数 
	 * @param length 随机数的位数
	 */
	public static String genRandom(int length) {
		String base = "qwertyuioplkjhgfdsazxcvbnmQAZWSXEDCRFVTGBYHNUJMIKLOP0123456789";
		StringBuffer sb = new StringBuffer();
		Random rd = new Random();
		for(int i=0;i<length;i++) {
			sb.append(base.charAt(rd.nextInt(base.length())));
		}
		return sb.toString();
	}
	
	public static String generateId() {
		return generateId(null);
	}
	
	/**
	 * id前缀
	 * @param prefix
	 * @return
	 */
	public static String generateId(String prefix) {
		return generateId(prefix, 0);
	}
	
	public static String generateId(String prefix, int randLength) {
		return generateId(prefix, randLength, false);
	}
	
	public static String generateId(String prefix, boolean fill) {
		return generateId(prefix, 0, fill);
	}
	
	/**
	 * id前缀
	 * @param prefix
	 * @return
	 */
	public static String generateId(String prefix, int randLength, boolean fill) {
		prefix = StringUtils.isBlank(prefix)?"":prefix;
		randLength = randLength < 1 ? 7 : randLength;
		int maxRandVal = new BigDecimal(Math.pow(10, randLength)).intValue();
		int randNum = new Random().nextInt(maxRandVal - 1);
		String origId = DateUtil.formatDate(new Date(), "yyyyMMddHHmmssSSS") + randNum;
		if(!fill) {
			return origId;
		}
		
		int size = origId.length()/2;
		int beginIndex = 0;
		StringBuilder newId = new StringBuilder(prefix).append(origId.substring(0, 4));
		int offset = 0;
		boolean fillZero = false;
		for (int i = 0; i < size; i++) {
			fillZero = false;
			if(i == 0 || i == 1) {//年份不填充0
				offset = 0;
				fillZero = false;
			}else if(i == 2 || i == 3 || i == 4) {//月份、天、小时 从A开始，offset=11
				offset = 11;
				fillZero = false;
			}else {
				offset = 0;
				fillZero = true;
			}
			beginIndex = 2*i;
			newId.append(convert(origId.substring(beginIndex, beginIndex+2), offset, fillZero));
		}
		return newId.toString();
	}
	
	private static char[] convert(String c, int offset, boolean fillZero) {
		int index = NumberUtil.toInt(c) + offset;
		if(index > 59) {
			return new char[]{'z', NUM_TO_CHAR_DICT[index%60]};
		}
		if(fillZero) {
			return new char[]{'0', NUM_TO_CHAR_DICT[index]};
		}
		return new char[]{NUM_TO_CHAR_DICT[index]};
	}
}
